package cn.com.huak.www.sell.converter;

import cn.com.huak.www.sell.dataObject.OrderDetail;
import cn.com.huak.www.sell.dto.OrderDTO;
import cn.com.huak.www.sell.enums.ResultEnum;
import cn.com.huak.www.sell.exception.OrderException;
import cn.com.huak.www.sell.form.OrderForm;
import com.fasterxml.jackson.databind.JavaType;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author huak@wanggang
 * @date 2019/1/1 23:29
 */
@Slf4j
public class OrderForm2OrderDTOConverter {

    /* 将orderForm转换成orderDTO */
    public static OrderDTO convert(OrderForm orderForm){
        if(orderForm == null){
            throw new OrderException(ResultEnum.ORDER_FORM_ERROR);
        }
        /* json转换 */
        Gson gson = new Gson();

        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerName(orderForm.getName());

        List<OrderDetail> orderDetails = null;
        try{
            orderDetails = gson.fromJson(orderForm.getItems(), new TypeToken<List<OrderDetail>>(){}.getType());
        }catch (Exception e){
            log.error("【json转换】json转换失败.....",e);
            throw new OrderException(ResultEnum.JSON_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetails);

        // 返回结果
        return orderDTO;
    }
}
